package com.yips.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yips.domain.entity.SysMenu;
import com.yips.service.SysMenuService;
import com.yips.mapper.SysMenuMapper;
import com.yips.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Gralt of Rivia
 * @description 针对表【sys_menu】的数据库操作Service实现
 * @createDate 2022-05-08 11:27:11
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
        implements SysMenuService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public Collection<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = menuMapper.selectMenuTreeByUserId(userId);
        return getChildPerms(menus, 0);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param menus     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    private List<SysMenu> getChildPerms(List<SysMenu> menus, int parentId) {
        List<SysMenu> returnList = new ArrayList<>();
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(menus, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表,不断查询并设置自身子节点
     *
     * @param menus
     * @param t
     */
    private void recursionFn(List<SysMenu> menus, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(menus, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(menus, tChild)) {
                recursionFn(menus, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> menus, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        Iterator<SysMenu> it = menus.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

}




